package com.mi.rof.interceptor;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mi.rof.entity.SystemException;
import com.mi.rof.entity.enums.ExceptionEnum;
import com.mi.rof.entity.vo.UserInfoVo;
import com.mi.rof.user.service.TokenService;
import com.mi.rof.utils.UserThreadLocal;
import com.mi.rof.entity.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * @author zwq
 */
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    /**
     * 设置一个刷新过期时间门槛为30分钟
     */
    private static final long REFRESH_THRESHOLD = 1000 * 60 * 60*24L ;
    private static final long TIME_OUT = 1000 * 60 * 60 * 24L;

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    @Resource
    private TokenService tokenService;

    long start = System.currentTimeMillis();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        start = System.currentTimeMillis();

        String token = request.getHeader("Authorization");
        log.info("================ request start ================");
        String requestUrl = request.getRequestURI();
        log.info("request uri: {}", requestUrl);
        log.info("request method: method", request.getMethod());

        if (StringUtils.isBlank(token)) {
            throw new SystemException(ExceptionEnum.NO_LOGIN.getCode(),
                    ExceptionEnum.NO_LOGIN.getMsg());
        }
        UserInfoVo userInfoVo = tokenService.checkToken(token);
        if (ObjectUtil.isNull(userInfoVo)||ObjectUtil.isEmpty(userInfoVo)) {
            throw new SystemException(ExceptionEnum.NO_LOGIN.getCode(),
                    ExceptionEnum.NO_LOGIN.getMsg());
        }

        //检查redis中是否有该用户的id

        String  userId =String.valueOf(userInfoVo.getUserId());
        String tokenRedis = stringRedisTemplate.opsForValue().get(userId);

        if (!token.equals(tokenRedis)) {
            throw new SystemException(ExceptionEnum.NO_LOGIN.getCode(),
                    ExceptionEnum.NO_LOGIN.getMsg());
        }
        // 查看token是否过期 未过期则刷新过期时间
        if((stringRedisTemplate.getExpire(userId) - System.currentTimeMillis())< REFRESH_THRESHOLD){
            stringRedisTemplate.expire(userId,System.currentTimeMillis()+TIME_OUT, TimeUnit.MILLISECONDS);
        }

        UserThreadLocal.put(userInfoVo);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        log.info("Interceptor cost={}", System.currentTimeMillis() - start);
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        //空方法
    }
}